package qj.util.swing;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import qj.util.SwingUtil;
import qj.util.funct.P0;

public class MapTable {

	
	private DefaultTableModel model = new DefaultTableModel(new Object[] {"Key", "Value"}, 0);
	public Component jtable = new JTable(model);
	public Component comp = new JScrollPane(jtable);
	{
		comp.setPreferredSize(new Dimension(200, 200));
	}
	HashMap<String, Object> data = new HashMap<String, Object>();
	
	ArrayList<String> keys = new ArrayList<String>();

	public void clear() {
		data.clear();
		for (int i = 0; i < model.getRowCount(); i++) {
			model.setValueAt("", i, 1);
		}
	}
	public void putAll(Map<String, ?> values) {
		clear();
		for (Entry<String, ?> entry : values.entrySet()) {
			set(entry.getKey(), entry.getValue());
		}
	}
	
	public void onInserting(final P0 action) {
		SwingUtil.onKeyDown(jtable, KeyEvent.VK_INSERT, action);
		SwingUtil.onDoubleClick(comp, new P0() {public void e() {
			if (data.isEmpty()) {
				action.e();
			}
		}});
	}

	public void setEntry(String key, Map<String, Object> values) {
		set(key, values.get(key));
	}
	public void set(String key, Object value) {
		data.put(key, value);
		int index = Collections.binarySearch(keys, key);
		if (index > -1) {
			model.setValueAt(value, index, 1);
		} else {
			int insertPoint = -index - 1;
			keys.add(insertPoint, key);
			model.insertRow(insertPoint, new Object[] {key, value});
//			keys.in
		}
	}
	
	@SuppressWarnings("rawtypes")
	public HashMap getData() {
		return data;
	}
	
}
